package com.yami.shop.platform.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.dto.BlogSwitchDTO;
import com.yami.shop.bean.enums.SendType;
import com.yami.shop.bean.event.SendPersonMessageEvent;
import com.yami.shop.bean.model.Blog;
import com.yami.shop.bean.model.BlogSort;
import com.yami.shop.bean.model.Tag;
import com.yami.shop.bean.param.NotifyTemplateParam;
import com.yami.shop.bean.vo.BlogVO;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ResponseEnum;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.StringUtils;
import com.yami.shop.security.platform.util.SecurityUtils;
import com.yami.shop.service.BlogService;
import com.yami.shop.service.BlogSortService;
import com.yami.shop.service.SysConfigService;
import com.yami.shop.service.TagService;
import com.yami.shop.sys.common.model.SysUser;
import com.yami.shop.sys.common.service.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 功能描述: 广场
 * @Author: LSR
 * @Date: 2022/12/28 10:00
 */

@RestController
@RequestMapping("/admin/blog")
public class BlogController {

    @Autowired
    private BlogService blogService;
    @Autowired
    private BlogSortService blogSortService;
    @Autowired
    private TagService tagService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private ApplicationContext applicationContext;


    @GetMapping("/page")
    @Operation(summary =  "根据参数分页获取平台品牌列表", description = "根据参数分页获取平台品牌列表")
    public ServerResponseEntity<IPage<Blog>> page(PageParam<Blog> page, BlogVO blog) {
        LambdaQueryWrapper<Blog> blogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(ObjectUtil.isNotEmpty(blog.getTitle())){
            blogLambdaQueryWrapper.like(Blog::getTitle,blog.getTitle());
        }
        if(ObjectUtil.isNotEmpty(blog.getBlogSortUid())){
            blogLambdaQueryWrapper.eq(Blog::getBlogSortUid,blog.getBlogSortUid());
        }
//        if(ObjectUtil.isNotEmpty(blog.getTagUid())){
//            blogLambdaQueryWrapper.like(Blog::getTagUid,blog.getTagUid());
//        }
        if(ObjectUtil.isNotEmpty(blog.getLevel())){
            blogLambdaQueryWrapper.eq(Blog::getLevel,blog.getLevel());
        }
        if(ObjectUtil.isNotEmpty(blog.getIsOriginal())){
            blogLambdaQueryWrapper.eq(Blog::getIsOriginal,blog.getIsOriginal());
        }
        if(ObjectUtil.isNotEmpty(blog.getIsPublish())){
            blogLambdaQueryWrapper.eq(Blog::getIsPublish,blog.getIsPublish());
        }
        if(ObjectUtil.isNotEmpty(blog.getStatus()) && blog.getStatus() != 0){
            blogLambdaQueryWrapper.eq(Blog::getStatus,blog.getStatus());
        }else{
            blogLambdaQueryWrapper.ne(Blog::getStatus,0);
        }
        if(ObjectUtil.isNotEmpty(blog.getArticleSource())){
            blogLambdaQueryWrapper.eq(Blog::getArticleSource,blog.getArticleSource());
        }
        if(ObjectUtil.isNotEmpty(blog.getAuditType())){
            blogLambdaQueryWrapper.eq(Blog::getAuditType,blog.getAuditType());
        }
        if(ObjectUtil.isNotEmpty(blog.getType())){
            blogLambdaQueryWrapper.eq(Blog::getType,blog.getType());//博客
        }
        blogLambdaQueryWrapper.orderByDesc(Blog::getCreateTime);
        // 获取分页博客
        IPage<Blog> brandList = blogService.page(page, blogLambdaQueryWrapper);
        // 获取分类信息
        List<Long> blogSortIds = brandList.getRecords().stream().filter(blog1 -> ObjectUtil.isNotEmpty(blog1.getBlogSortUid())).map(Blog::getBlogSortUid).collect(Collectors.toList());
        List<BlogSort> blogSorts = new ArrayList<>();
        if(ObjectUtil.isNotEmpty(blogSortIds)){
            blogSorts = blogSortService.listByIds(blogSortIds);
        }
        Map<Long, BlogSort> blogSortMap = blogSorts.stream().collect(Collectors.toMap(BlogSort::getUid, Function.identity()));
        // 获取标签信息
        List<String> tagIdAlls = new ArrayList<>();
        List<String> tagIds = brandList.getRecords().stream().filter(blog1 -> StrUtil.isNotEmpty(blog1.getTagUid())).map(Blog::getTagUid).collect(Collectors.toList());
        List<Tag> tags = new ArrayList<>();
        if(ObjectUtil.isNotEmpty(tagIds)){
            tagIds.forEach(s->{
                if(s.contains(",")){
                    String[] split = s.split(",");
                    tagIdAlls.addAll(Arrays.asList(split)) ;
                }else if(StrUtil.isNotEmpty(s)){
                    tagIdAlls.add(s);
                }
            });
            tagIds = tagIdAlls.stream().distinct().collect(Collectors.toList());
            tags = tagService.listByIds(tagIds);
        }
        Map<Long, Tag> tagsMap = tags.stream().collect(Collectors.toMap(Tag::getUid, Function.identity()));
        brandList.getRecords().stream().forEach(item->{
            //设置分类
            if (ObjectUtil.isNotEmpty(item.getBlogSortUid())) {
                item.setBlogSort(blogSortMap.get(item.getBlogSortUid()));
            }
            //获取标签
            if (ObjectUtil.isNotEmpty(item.getTagUid())) {
                List<String> tagUidsTemp = Arrays.asList(item.getTagUid().split(","));
                List<Tag> tagListTemp = new ArrayList<Tag>();
                tagUidsTemp.forEach(tag -> {
                    tagListTemp.add(tagsMap.get(Long.parseLong(tag)));
                });
                item.setTagList(tagListTemp);
            }
        });
        return ServerResponseEntity.success(brandList);
    }

    @GetMapping("/getById/{id}")
    @Operation(summary =  "博客详情", description = "博客详情")
    public ServerResponseEntity<Blog> getById(@PathVariable("id") Long id){
        Blog blog = blogService.getById(id);
        return ServerResponseEntity.success(blog);
    }
    
    
    @PostMapping
    @Operation(summary =  "新增广场信息", description = "新增广场信息")
    public ServerResponseEntity<Void> saveTag(@RequestBody Blog blog){
        blog.setStatus(1);//未审核
        blog.setUserUid(SecurityUtils.getSysUser().getUserId().toString());
        blog.setArticleSource(2);//平台添加
        blog.setType(0);//博客
        BlogSwitchDTO blogSwitchDTO = sysConfigService.getSysConfigObject(Constant.BLOG_SWITCH_CONFIG, BlogSwitchDTO.class);
        Integer auditType = 0;
        if (Objects.nonNull(blogSwitchDTO) && blogSwitchDTO.getSquareAudit()) {
            auditType = 1;
        }
        blog.setAuditType(auditType);
        if ("1".equals(blog.getIsOriginal())) {//原创
            // 获取平台信息
            SysUser byId = sysUserService.getById(SecurityUtils.getSysUser().getUserId());
            if (byId != null) {
                blog.setAuthor(byId.getNickName());
                blog.setArticlesPart("DTC++");
            }
        }
        blog.setCreateTime(new Date());
        blogService.saveData(blog);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @Operation(summary =  "修改广场信息", description = "修改广场信息")
    public ServerResponseEntity<Void> updateTag(@RequestBody Blog blog){
        blog.setStatus(1);//未审核
        if ("1".equals(blog.getIsOriginal())) {//原创
            // 获取平台信息
            SysUser byId = sysUserService.getById(SecurityUtils.getSysUser().getUserId());
            if (byId != null) {
                blog.setAuthor(byId.getNickName());
                blog.setArticlesPart("DTC++");
            }
        }
        blog.setUpdateTime(new Date());
        blogService.updateById(blog);
        return ServerResponseEntity.success();
    }

    @PostMapping(value ="/updatePublish")
    @Operation(summary =  "发布下架", description = "修改广场信息")
    public ServerResponseEntity<Void> updatePublish(@RequestBody Blog blog){
        Blog param = new Blog();
        param.setUid(blog.getUid());
        param.setIsPublish(blog.getIsPublish());
        blogService.updateById(blog);
        return ServerResponseEntity.success();
    }

    @DeleteMapping("/{uids}")
    @Operation(summary =  "删除", description = "修改广场信息")
    public ServerResponseEntity<Void> delBatchBlog(@PathVariable("uids") Long[] uids){
        List<Blog> blogs = blogService.listByIds(Arrays.asList(uids));
        List<Blog> collect = blogs.stream().filter(blog -> "1".equals(blog.getIsPublish())).collect(Collectors.toList());
        if(collect!=null && collect.size()>0){
            return ServerResponseEntity.showFailMsg("已发布的博客不能删除");
        }
        blogs.forEach(blog->blog.setStatus(0));
        blogService.updateBatchById(blogs);
        return ServerResponseEntity.success();
    }


    @PostMapping(value ="/audit")
    @Operation(summary =  "博客审核", description = "博客审核")
    public ServerResponseEntity<Void> audit(@RequestBody Blog blog) {
        if (blog.getStatus().equals(1) && StringUtils.isEmpty(blog.getReason())) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "驳回时原因不能为空！");
        }
        Blog one = blogService.getById(blog.getUid());
        if (Objects.isNull(one) || !one.getStatus().equals(3)) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "原文不存在或已审核！");
        }
        if (blog.getStatus().equals(1)) {
            one.setStatus(2); // 驳回
        } else if (blog.getStatus().equals(0)) {
            one.setStatus(1);
        } else {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "审核结果异常！");
        }
        one.setReason(blog.getReason());
        blogService.updateById(one);

        if (blog.getStatus().equals(1) && one.getArticleSource().equals(1)) {
            // 驳回后给c端发送消息
            NotifyTemplateParam shopParam = new NotifyTemplateParam();
            shopParam.setShopId(Constant.PLATFORM_SHOP_ID);
            shopParam.setSendType(SendType.BLOG_REJECT.getValue());
            shopParam.setUserId(one.getUserUid());
            shopParam.setTitle(blog.getReason());
            shopParam.setContent(one.getContent());
            if (one.getType().equals(0)) {
                shopParam.setToTypeName("广场");
            } else if (one.getType().equals(2)) {
                shopParam.setToTypeName("圈子");
            }
            applicationContext.publishEvent(new SendPersonMessageEvent(shopParam));
        }
        return ServerResponseEntity.success();
    }
    


    @GetMapping("/pageAudit")
    @Operation(summary =  "审核店铺博客列表", description = "根据参数分页获取平台品牌列表")
    public ServerResponseEntity<IPage<Blog>> pageAudit(PageParam<Blog> page, BlogVO blog) {
        LambdaQueryWrapper<Blog> blogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        blogLambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(blog.getTitle()),Blog::getTitle,blog.getTitle());
        if(ObjectUtil.isNotEmpty(blog.getStatus()) && blog.getStatus() != 0){
            blogLambdaQueryWrapper.eq(Blog::getStatus,blog.getStatus());
        }else{
            blogLambdaQueryWrapper.ne(Blog::getStatus,0);
        }
        blogLambdaQueryWrapper.eq(Blog::getArticleSource,0);//来自店铺
        blogLambdaQueryWrapper.eq(Blog::getType,0);//博客
        blogLambdaQueryWrapper.orderByDesc(Blog::getCreateTime);
        // 获取分页博客
        IPage<Blog> brandList = blogService.page(page, blogLambdaQueryWrapper);
        // 获取分类信息
        List<Long> blogSortIds = brandList.getRecords().stream().map(Blog::getBlogSortUid).collect(Collectors.toList());
        List<BlogSort> blogSorts = new ArrayList<>();
        if(ObjectUtil.isNotEmpty(blogSortIds)){
            blogSorts = blogSortService.listByIds(blogSortIds);
        }
        Map<Long, BlogSort> blogSortMap = blogSorts.stream().collect(Collectors.toMap(BlogSort::getUid, Function.identity()));
        // 获取标签信息
        List<String> tagIds = brandList.getRecords().stream().map(Blog::getTagUid).collect(Collectors.toList());
        List<Tag> tags = new ArrayList<>();
        if(ObjectUtil.isNotEmpty(tagIds)){
            tags = tagService.listByIds(tagIds);
        }
        Map<Long, Tag> tagsMap = tags.stream().collect(Collectors.toMap(Tag::getUid, Function.identity()));
        brandList.getRecords().stream().forEach(item->{
            //设置分类
            if (ObjectUtil.isNotEmpty(item.getBlogSortUid())) {
                item.setBlogSort(blogSortMap.get(item.getBlogSortUid()));
            }
            //获取标签
            if (ObjectUtil.isNotEmpty(item.getTagUid())) {
                List<String> tagUidsTemp = Arrays.asList(item.getTagUid().split(","));
                List<Tag> tagListTemp = new ArrayList<Tag>();
                tagUidsTemp.forEach(tag -> {
                    tagListTemp.add(tagsMap.get(Long.parseLong(tag)));
                });
                item.setTagList(tagListTemp);
            }
        });
        return ServerResponseEntity.success(brandList);
    }

    @PostMapping(value ="/updateAudit")
    @Operation(summary =  "审核店铺博客", description = "根据参数分页获取平台品牌列表")
    public ServerResponseEntity<Void> updateAudit(@RequestBody Blog blog){
        Blog param = new Blog();
        param.setUid(blog.getUid());
        if(blog.getStatus()==2){
            param.setReason(blog.getReason());
        }else{
            param.setReason("");
        }
        param.setStatus(blog.getStatus());
        blogService.updateById(param);
        return ServerResponseEntity.success();
    }

}
